<?php


namespace App\Http\Controllers\Supplier;


use App\Http\Controllers\Supplier\BaseController;
use App\Models\NewAdmin;
use App\Models\ShopTrans;
use App\Models\ShopUser;
use App\Models\ShopWithdrawal;
use App\Services\CommonService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WithdrawalController extends BaseController
{
    /**
     * 提现列表
     * @param Request $request
     * @return false|string
     */
    public function withdrawalList(Request $request){
        $payeeName = $request->input('payeeName','');
        $payeeAccount = $request->input('payeeAccount','');
        $arrivalTime = $request->input('arrivalTime','');
        $status = $request->input('status','');
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',10);
        $where[] = ['w.member_id',$this->shopUser['member_id']];
        if($payeeName){
            $where[] = ['w.payee_name','like','%'.$payeeName.'%'];
        }
        if($payeeAccount){
            $where[] = ['w.payee_account','like','%'.$payeeAccount.'%'];
        }
        if($status){
            $where[] = ['w.status',$status];
        }
        if($arrivalTime){
            $arrivalTime = explode('~', $arrivalTime);
            $where[] = ['w.apply_time','>=',$arrivalTime[0]];
            $where[] = ['w.apply_time','<',$arrivalTime[1]];
        }
        $list = ShopWithdrawal::from('sp_shop_withdrawal as w')
            ->select('w.id','w.member_id','w.withdrawal_amount','w.payee_name','w.payee_account','w.alipay_trade_no','w.out_biz_no','w.out_biz_no'
                ,'w.pay_type','w.status','w.refuse_reason','w.apply_time','w.check_time','w.admin_id','w.arrival_time'
            )
            ->where($where)
            ->orderBy('w.id','desc')
            ->paginate($pageSize);
        $list = obToArray($list);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }

    /**
     * 申请提现
     * @param Request $request
     * @return false|string
     */
    public function withdrawalApply(Request $request){
        try{
            $amount = $request->input('amount','');
            if(!$amount){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            if(!$this->shopUser['payeename'] || !$this->shopUser['alipayaccount']){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未设置提现账户');
            }
            if (!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $amount)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'提现金额错误');
            }
            if($amount < ShopWithdrawal::WITHDRAWAL_AMOUNT_LIMIT){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'提现金额不能低于'.ShopWithdrawal::WITHDRAWAL_AMOUNT_LIMIT.'元');
            }
            $shop_balance = ShopUser::where(['member_id'=>$this->shopUser['member_id']])->value('shop_balance');
            if($amount > $shop_balance){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'账户余额不足');
            }
            $apply_time = ShopWithdrawal::where(['member_id'=>$this->shopUser['member_id'],'status'=>ShopWithdrawal::WITHDRAWAL_STATUS_REVIEWED])->orderBy('id','desc')->value('apply_time');
            if(strtotime($apply_time) == time()){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请稍后再试');
            }
            DB::beginTransaction();
            $data = [
                'member_id'=>$this->shopUser['member_id'],
                'withdrawal_amount'=>$amount,
                'payee_name'=>$this->shopUser['payeename'],
                'payee_account'=>$this->shopUser['alipayaccount'],
                'apply_time'=>dateFormat(time()),
                'apply_admin_id'=>$this->users['id'],
            ];
            $res = ShopWithdrawal::insertGetId($data);
            if($res){
                $shop_trans_data = array(
                    'member_id' => $this->shopUser['member_id'],
                    'amount' => -$amount,
                    'before_balance' => $this->shopUser['shop_balance'],
                    'after_balance' => $this->shopUser['shop_balance']  - $amount,
                    'trans_type' => ShopTrans::ORDER_TRANS_TYPE_WITHDRAWAL,
                    'remarks' => '商户提现申请',
                    'create_time' => dateFormat(time()),
                );
                ShopTrans::addData($shop_trans_data);
                ShopUser::where(['member_id'=>$this->shopUser['member_id']])->increment('frozen_amount',$amount);
                ShopUser::where(['member_id'=>$this->shopUser['member_id']])->decrement('shop_balance',$amount);
                DB::commit();
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'申请成功',['withdrawal_id'=>$res]);
            }else{
                DB::rollBack();
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'申请失败');
            }
        }catch (\Exception $exception){
            DB::rollBack();
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'申请失败');
        }
    }

    /**
     * 提现信息
     * @param Request $request
     * @return false|string
     */
    public function withdrawalInfo(Request $request){
        $withdrawal_id = $request->input('withdrawal_id','');
        if(!$withdrawal_id){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }
        $member_id = $this->shopUser['member_id'];
        $data['shop_balance'] = $this->shopUser['shop_balance'];
        $data['frozen_amount'] = $this->shopUser['frozen_amount'];
        $withdrawal = ShopWithdrawal::where([['id',$withdrawal_id],['member_id',$member_id]])->select('withdrawal_amount','pay_type','payee_name','payee_account','apply_time','status','refuse_reason','check_time')->first();
        $withdrawal = obToArray($withdrawal);
        if(!empty($withdrawal)){
            $withdrawal['status_name'] = ShopWithdrawal::WITHDRAWAL_STATUS_LIST[$withdrawal['status']];
            $withdrawal['pay_type'] = ShopWithdrawal::WITHDRAWAL_TYPE_LIST[$withdrawal['pay_type']];
        }
        $data['withdrawal_info'] = $withdrawal;

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }

}
